# -*- coding: utf-8 -*-
# filename: basic.py
from urllib import request
import time
import json
import os

class Basic:
    def __init__(self):
        self.__accessToken = ''
        self.__outTime = 0    
        self.__accessTokenSavePath = "access_token.txt"
        if not os.path.exists(self.__accessTokenSavePath):
        	with open(self.__accessTokenSavePath,"w") as f:
        		save_dict = {"accessToken":'',"outTime":0}
        		json.dump(save_dict,f)

        


    def __real_get_access_token(self):  
    	try:      
	    	appId = "wx2ab2f364a274ed46"        
	    	appSecret = "8ce099a891c988380034f8c6f416bb79"        
	    	postUrl = ("https://api.weixin.qq.com/cgi-bin/token?grant_type="
	    	               "client_credential&appid=%s&secret=%s" % (appId, appSecret)) 	    	     
	    	urlResp = request.urlopen(postUrl) 

	    	urlResp = json.loads(urlResp.read()) 
	    	print(urlResp)                
	    	self.__accessToken = urlResp['access_token']    
	    	self.__expires_in = urlResp['expires_in']  
	    	self.__outTime = int(time.time()) + (self.__expires_in-20)*1000
	    	with open(self.__accessTokenSavePath,"w") as f:
        		save_dict = {"accessToken":self.__accessToken,"outTime":self.__outTime}
        		json.dump(save_dict,f)
    	except:
	    	print('INFO: Erro !')
	    	time.sleep(2)  
    def get_access_token(self):    
    	with open(self.__accessTokenSavePath,'r') as load_f:
    		load_dict = json.load(load_f)
    		self.__accessToken  = load_dict['accessToken']
    		print(load_dict)
    	if load_dict['outTime'] < int(time.time()):            
    		self.__real_get_access_token()        
    	return self.__accessToken    
   
if __name__ == '__main__':
	basic = Basic()
	print("get_access_token:",basic.get_access_token())